/*
 * @Date: 2025-03-07 09:00:28
 * @LastEditTime: 2025-03-28 09:33:19
 * @FilePath: \LeagueBard\frontend\src\LcuApi\clientOnline.ts
 * @Description: 客户端在线状态
 */
import { getMyInfo } from '@/api/client/userApi'
import ClientGameflow from '@/LcuApi/clientGameflow'
import { useClientStore } from '@/stores/client'
import { useMessageListStore } from '@/stores/messgelist'

import { GetClientInfo, GetClientIsRunning } from '@wails/client/clientfunc'
import { Events } from '@wailsio/runtime';

class ClientOnline {
  private Gameflow: any
  private userInfoUUid: string

  constructor() {
    this.Gameflow = {}
    this.userInfoUUid = ''
  }

  getClientInfo() {
    // 监听游戏流
    this.Gameflow = new ClientGameflow()

    // 获取客户端信息
    GetClientInfo().then(({ IsRunning, Info }) => {
      useClientStore().leagueRunning = IsRunning || false
      if (IsRunning) {
        useClientStore().clientInfo = Info || {}
        this.getUserInfo()
      } else {
        useClientStore().clientInfo = {}
        useClientStore().userInfo = {}
      }
    })

    // 监听客户端信息
    Events.On('clientRunStateChange', ({ data }) => {
      if (data.length > 0) {
        const { IsRunning, Info } = data[0]
        useClientStore().leagueRunning = IsRunning || false
        if (!IsRunning) {
          useClientStore().clientInfo = {}
          useClientStore().userInfo = {}
        } else {
          useClientStore().clientInfo = Info || {}
          // userInfo 会由客户端主动推送，这里只监听是否有port
        }
      }
    })

    // 监听当前召唤师信息
    useMessageListStore().addMessage({
      name: 'CurrentSummoner',
      trigger: ({ data }) => {
        // 防止在获取port前就触发
        if (useClientStore().clientInfo['--app-port']) {
          useClientStore().userInfo = data || {}
        }
      },
    })
  }

  getUserInfo() {
    if (!useClientStore().clientInfo['--app-port']) {
      return
    }
    // 获取用户信息
    getMyInfo().then((userInfo) => {
      useClientStore().userInfo = userInfo || {}
    })
    this.Gameflow.getCurrentGameFlow()
  }
}

export default new ClientOnline()
